﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using System.Windows;
using Telerik.Windows.Controls;
using TruckScale.Helpers;
using TruckScale.Models;
using static TruckScale.Helpers.LogHelper;

namespace TruckScale.ViewModels
{
  public partial class MainViewModel
  {
    public string InfoBar { get; set; } //绑定界面属性：错误信息提示
    public string Password { get; set; }  //绑定界面属性：密码
    //public string InputBoxHeight { get; set; } //绑定界面属性：输入框的高度
    public bool ShowDBCnnBtn { get; set; }

    private UserModel _selectedUser;
    private bool _autoStart;
    private bool _autoLogin;
    private bool _storePwd;

    public List<UserModel> UserList { get; set; }  //绑定界面属性：用户列表

    public UserModel SelectedUser //绑定界面属性：用户名
    {
      get => _selectedUser;
      set
      {
        _selectedUser = value;
        Password = null; //切换用户后重置密码框
      }
    }

    public bool AutoStart
    {
      get { return _autoStart; }
      set
      {
        _autoStart = value;

        Global._weighConfig["AutoStart"] = value.ToString();
        WeighConfigModel.UpdateConfig("AutoStart", value.ToString());

        if (value)
        {
          StartUpHelper.SetAutoStart(true, "TruckScale.exe");
        }
        else
        {
          StartUpHelper.SetAutoStart(false, "TruckScale.exe");
        }
      }
    }  //绑定界面属性：开机自启
    public bool AutoLogin
    {
      get { return _autoLogin; }
      set
      {
        _autoLogin = value;

        Global._weighConfig["AutoLogin"] = value.ToString();
        WeighConfigModel.UpdateConfig("AutoLogin", value.ToString());
      }
    }  //绑定界面属性：自动登录
    public bool StorePwd
    {
      get { return _storePwd; }
      set
      {
        _storePwd = value;

        if (value)
        {
          if (File.Exists("Data\\user.dat"))
          {
            using (Stream s = File.Open("Data\\user.dat", FileMode.Open))
            {
              if (s.Length > 0)
              {
                BinaryFormatter bf = new BinaryFormatter();
                UserModel LastUser = bf.Deserialize(s) as UserModel;
                SelectedUser = UserList.Find(u => u.UserId == LastUser.UserId);
                Password = SelectedUser?.LoginPwd;
              }
            }
          }
        }
        else
        {
          File.Delete("Data\\user.dat");
        }

        Global._weighConfig["StorePwd"] = value.ToString();
        WeighConfigModel.UpdateConfig("StorePwd", value.ToString());
      }
    }  //绑定界面属性：保存密码

    public DelegateCommand LoginCommand { get; private set; } //绑定界面命令：登录
    public DelegateCommand LogoutCommand { get; private set; } //绑定界面命令：登出

    private void OnLoginCommandExecuted(object obj)
    {
      if (SelectedUser != null)
      {
        if ((string.IsNullOrEmpty(SelectedUser.LoginPwd) && string.IsNullOrEmpty(Password)) //密码为空或者Null
          || SelectedUser.LoginPwd == Password) //用户名密码相同，验证通过，保存到全局，打开主窗口
        {
          Global._currentUser = SelectedUser;

          SetLog(SelectedUser.UserName + "登录系统", LogHelper.LogType.OperationLogger);
          InfoBar = "";

          using (Stream s = File.Open("Data\\user.dat", FileMode.OpenOrCreate))
          {
            BinaryFormatter bf = new BinaryFormatter();
            bf.Serialize(s, SelectedUser);
          }

          //BackupHelper.AutoBackup();
          DBBackupViewModel dbbackvm = new DBBackupViewModel();
          dbbackvm.ExecuteAutoBackup();

          AsposeHelper.InitializeAsposeCells();

          IsLogin = true;
        }
        else
        {
          InfoBar = "密码错误";
        }
      }
      else
      {
        InfoBar = "请选择用户";
      }
    }

    private void OnLogoutCommandExecuted(object obj)
    {
      if (Global._currentUser != null)
      {
        SetLog(Global._currentUser.UserName + "退出系统", LogType.OperationLogger);
        AutoLogin = false;
        IsLogin = false;
        Global._currentUser = null;
      }

      //用户数据有可能修改，需要重新加载用户数据
      InitLoginProps();
    }

    private void InitLoginProps()
    {
      UserList = UserModel.SelectValidUser();

      if (UserList == null)
      {
        InfoBar = "数据库连接失败！";
        ShowDBCnnBtn = true;
        return;
      }

      //InputBoxHeight = (1.4 * Convert.ToDouble(Global._config["MainFontSize"]) + 10).ToString();
      AutoStart = Convert.ToBoolean(Global._weighConfig["AutoStart"]);
      StorePwd = Convert.ToBoolean(Global._weighConfig["StorePwd"]);
      AutoLogin = Convert.ToBoolean(Global._weighConfig["AutoLogin"]);

      if (StorePwd)
      {
        if (File.Exists("Data\\user.dat"))
        {
          using (Stream s = File.Open("Data\\user.dat", FileMode.Open))
          {
            if (s.Length > 0)
            {
              BinaryFormatter bf = new BinaryFormatter();
              UserModel LastUser = bf.Deserialize(s) as UserModel;
              SelectedUser = UserList.Find(u => u.UserId == LastUser.UserId);
              Password = SelectedUser?.LoginPwd;
            }
          }
        }
      }

      if (AutoLogin)
      {
        OnLoginCommandExecuted(null);
      }

      CheckDevice(RegisterHelper.GetHdInfo());
    }

    private void InitLoginCommands()
    {
      LoginCommand = new DelegateCommand(OnLoginCommandExecuted);
      LogoutCommand = new DelegateCommand(OnLogoutCommandExecuted);
    }

    private async void CheckDevice(string machineCode)
    {
      try
      {
        // 使用工具类发送请求并获取设备的可用状态
        bool isAvailable = await HttpClientHelper.IsDeviceAvailable(machineCode);

        // 根据 available 的值执行后续操作
        if (isAvailable)
        {
          Console.WriteLine("设备可用");
        }
        else
        {
          SetLog("设备不可用", LogType.OperationLogger);
          Application.Current.MainWindow.Close();
        }
      }
      catch (Exception ex)
      {
        // 处理异常
        SetLog($"异常: {ex.Message}", LogType.OperationLogger);
        //在此处判断，无网络的情况下是否可以继续打开
        //Application.Current.MainWindow.Close();
      }
    }
  }
}
